package cn.fancy.sdk.login.view;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.fancy.sdk.FancyManager;
import cn.fancy.sdk.QdRegisterCallback;
import cn.fancy.sdk.baseview.BaseView;
import cn.fancy.sdk.baseview.IActivityManager;
import cn.fancy.sdk.common.utils.LoginSwitchManage;
import cn.fancy.sdk.common.utils.NetworkImpl;
import cn.fancy.sdk.common.utils.ResUtil;
import cn.fancy.sdk.common.utils.SdkAsyncTask;
import cn.fancy.sdk.config.GlobalConfig;
import cn.fancy.sdk.entity.GuildBaseInfo;
import cn.fancy.sdk.login.QdLoginResult;
import cn.fancy.sdk.login.utils.AccountHelper;
import cn.fancy.sdk.login.utils.AccountHelper.Local_Account;
import cn.fancy.sdk.login.utils.Checker;
import cn.fancy.sdk.login.utils.DBHelper;
import cn.fancy.sdk.login.utils.HttpReq;
import cn.fancy.sdk.utils.CommMessage;
import cn.fancy.sdk.utils.SpMmkvUtils;
import cn.fancy.sdk.utils.TipMessSingle;
import com.bytedance.applog.game.GameReportHelper;
import java.util.ArrayList;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONException;
import org.json.JSONObject;

public class BindPhoneMustView extends BaseView {
    
    IActivityManager activityMgr;
    private Activity ownerActivity;
    Context mContext;
    LayoutInflater inflater;
    DBHelper dbHelper;
    String bind_acount = "";
    String ucode = "";
    private boolean isMustBind;
    Timer timer;
    Handler handler;
    SdkAsyncTask<String> bindPhoneAsyncTask = null;
    private EditText bind_phone_input, bind_code_input;
    private EditText et_true_name, et_verify_number;
    private TextView SendMess;
    QdLoginResult loginResultSucc;
    ArrayList<AccountHelper.Local_Account> local_valid_accts = new ArrayList<AccountHelper.Local_Account>();
    private String username;
    private String user_id;
    private String password;
    
    // must标记符，yes必须绑点X返登陆，no不必须点击X进游戏
    public BindPhoneMustView(Activity cActivity, IActivityManager activityMgr,
        boolean must, QdLoginResult loginResult, String upass, String user_id) {
        super(cActivity.getBaseContext(), ResUtil.getLayoutId(
            cActivity.getBaseContext(), "guild_bindphone_must"));
        if (must) {
            Toast.makeText(cActivity.getBaseContext(), TipMessSingle.seven_in,
                Toast.LENGTH_LONG).show();
        }
        mContext = cActivity.getBaseContext();
        isMustBind = must;
        loginResultSucc = loginResult;
        this.user_id = user_id;
        password=upass;
        
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what > 0) {
                    SendMess.setText(String.format("请%02d秒后重试", msg.what));
                } else {
                    SendMess.setText("重新获取");
                    SendMess.setEnabled(true);
                    timer.cancel();
                }
            }
        };
        
        this.activityMgr = activityMgr;
        ownerActivity = cActivity;
        inflater = LayoutInflater.from(this.getContext());
        dbHelper = DBHelper.getInstance(mContext);
        initView();
        try {
            initAccount();
        } catch (Exception e) {
            e.printStackTrace();
        }
        CommMessage.sBindAndReal = false;
    }
    
    private void initAccount() {
        // 先在本地sqlite 数据库中检测是否有用户名存在
        ArrayList<DBHelper.SDK_ACCOUNT> db_valid_accts = dbHelper.getAllValidAccounts();
        local_valid_accts = AccountHelper.getLocalAccountsAsArrayList(this.getContext(), true);
        AccountHelper.Local_Account account = AccountHelper
            .getLastestLoginAccountFromOldSdk(this.getContext());
        if (db_valid_accts.size() > 0) {
            DBHelper.SDK_ACCOUNT acc = db_valid_accts.get(0);
            acc.user_name = username;
        } else if (local_valid_accts.size() > 0) {
            Local_Account temp = local_valid_accts
                .get(local_valid_accts.size() - 1);
            temp.username = username;
        } else if (account.username != null && !"".equals(account.username)
            && account.password != null && !"".equals(account.password)) {
            
            account.last_login_time = System.currentTimeMillis();
            account.isValid = AccountHelper.ACCOUNT_VALID;
            AccountHelper.updateLocalAccounts(account);
        }
    }
    
    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        this.postInvalidate();
    }
    
    private void initView() {
        bind_phone_input = (EditText) this.findViewById(ResUtil.getId(mContext,
            "guild_bindmobile_mobile_main"));
        bind_phone_input.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        
        bind_code_input = (EditText) this.findViewById(ResUtil.getId(mContext,
            "guild_bindmobile_mess_main"));
        bind_code_input.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
    
        TextView confirmBtn = (TextView) this.findViewById(ResUtil.getId(mContext,
            "guild_bindmobile_confirm_main"));
        confirmBtn.setOnClickListener(this);
    
        ImageView cancleBtn = (ImageView) this.findViewById(ResUtil.getId(mContext,
            "guild_bindmobile_cancle_main"));
        cancleBtn.setOnClickListener(this);
    
        TextView guild_webus = (TextView) this.findViewById(ResUtil.getId(mContext,
            "guild_webus"));
        guild_webus.setOnClickListener(this);
        
        SendMess = (TextView) this.findViewById(ResUtil.getId(mContext,
            "guild_bindmobile_send_message_main"));
        SendMess.setOnClickListener(this);
        SendMess.setClickable(true);
        
        et_true_name = (EditText) this.findViewById(ResUtil.getId(mContext, "et_true_name"));
        et_verify_number = (EditText) this.findViewById(ResUtil.getId(mContext, "et_verify_number"));
        
        if (isMustBind) {
            activityMgr.setMessBind(true);
        }
    }
    
    @Override
    public void onClick(View v) {
        int vid = v.getId();
        if (vid == ResUtil.getId(mContext,
            "guild_bindmobile_send_message_main")) {
            getCodeRequest();
        } else if (vid == ResUtil.getId(mContext,
            "guild_bindmobile_confirm_main")) {
            ucode = bind_code_input.getText().toString().trim();
            doBindRequest();
        } else if (vid == ResUtil.getId(mContext, "guild_bindmobile_cancle_main")) {
            if (isMustBind) {
                GuildBaseInfo.getInstance().clearLogMap();
                activityMgr.NewpopViewFromStack();
                activityMgr.pushViewToStack(new LoginView(ownerActivity,
                    activityMgr));
            } else {
                if (GlobalConfig.sRegCard == 2) {
                    // 强制实名
                    Toast.makeText(mContext, TipMessSingle.nine_namenil,
                        Toast.LENGTH_LONG).show();
                    activityMgr.pushViewToStack(new RealViewMust(ownerActivity,
                        activityMgr, false));
                    return;
                } else if (GlobalConfig.sRegCard== 1) {
                    // 不强制实名
                    Toast.makeText(mContext, TipMessSingle.nine_namenil,
                        Toast.LENGTH_LONG).show();
                    activityMgr.pushViewToStack(new RealViewMust(ownerActivity,
                        activityMgr, true));
                    return;
                }
                // 直接进游戏
                Map<String, String> MessReal = GuildBaseInfo.getInstance()
                    .GetLoginAuMess();
                String username = MessReal.get("plat_user_name");
                String password = MessReal.get("password");
                startLogin(username, password);
                activityMgr.finishDialogOrActivity();
            }
        }
    }
    
    // 发送验证
    public void getCodeRequest() {
        final String uphone = bind_phone_input.getText().toString().trim();
        String mobile_format = Checker.checkPhoneNumber(uphone, mContext);
        if (!mobile_format.equals(Checker.IS_OK)) {
            Toast.makeText(mContext, TipMessSingle.three_mobilenil,
                Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, String> tempMap = GuildBaseInfo.getInstance().getSmscodeParamsWithPassGuide(
            getContext(), uphone, "send_phone_verify");
        
        if (tempMap == null) {
            Toast.makeText(mContext, "传入参数有误...", Toast.LENGTH_SHORT).show();
            return;
        }
        
        final Map<String, String> regMap = tempMap;
        bindPhoneAsyncTask = new SdkAsyncTask<String>() {
            @Override
            protected String doInBackground() {
                return HttpReq.doGuildRequest(regMap);
            }
            
            @Override
            protected void onPostExecute(String rst) {
                activityMgr.cancelWaitingDialog();
                if (rst == null) {
                    rst = "";
                }
                if (rst.equals("")) {
                    Toast.makeText(mContext, TipMessSingle.ten_networkerr,
                        Toast.LENGTH_LONG).show();
                    return;
                }
                Log.e("bindphonecoderst", "bindphonecoderst:" + rst);
                try {
                    JSONObject json = new JSONObject(rst);
                    String state = json.getString("state");
                    JSONObject jsonState = new JSONObject(state);
    
                    int code = jsonState.getInt("code");
                    String msgmsg = jsonState.optString("msg");
                    if (code != 1) {
                        Toast.makeText(getContext(), msgmsg, Toast.LENGTH_LONG)
                            .show();
                        return;
                    }
                    String msg = json.getString("data");
                    
                    JSONObject msgjson = new JSONObject(msg);
                    Log.e("bindphonemustsmscode", "bindphonemustsmscode"
                        + msgjson.optString("code"));
                    Toast.makeText(mContext, "获取成功，验证码有效时间为1小时",
                        Toast.LENGTH_LONG).show();
                    
                    SendMess.setEnabled(false);
                    timer = new Timer();
                    TimerTask timerTask = new TimerTask() {
                        int i = 55;
                        
                        @Override
                        public void run() {
                            Message msg = new Message();
                            msg.what = i--;
                            handler.sendMessage(msg);
                        }
                    };
                    timer.schedule(timerTask, 0, 1000);
                } catch (JSONException e) {
                    Log.d("BindPhone", "Server returns error msg");
                    e.printStackTrace();
                }
            }
            
            @Override
            public Activity getOwnerActivity() {
                return ownerActivity;
            }
            
            @Override
            protected void onCancelled() {
            }
            
        };
        bindPhoneAsyncTask.execute();
        activityMgr.showWaitingDialog();
    }
    
    public void doBindRequest() {
        final String uphone = bind_phone_input.getText().toString().trim();
        String mobile_format = Checker.checkPhoneNumber(uphone, mContext);
        if (!mobile_format.equals(Checker.IS_OK)) {
            Toast.makeText(mContext, TipMessSingle.three_mobilenil,
                Toast.LENGTH_SHORT).show();
            return;
        }
        if (!NetworkImpl.isNetworkConnected(getContext())) {
            Toast.makeText(mContext, TipMessSingle.ten_networkerr,
                Toast.LENGTH_LONG).show();
            return;
        }
        Map<String, String> tempMap = GuildBaseInfo.getInstance()
            .buildgetBindParamsMain(getContext(), uphone, "set_phone", ucode, user_id);
        if (tempMap == null) {
            Toast.makeText(mContext, "传入参数有误...", Toast.LENGTH_SHORT).show();
            return;
        }
        
        final Map<String, String> regMap = tempMap;
        bindPhoneAsyncTask = new SdkAsyncTask<String>() {
            @Override
            protected String doInBackground() {
                return HttpReq.doGuildRequest(regMap);
            }
            
            @Override
            protected void onPostExecute(String rst) {
                activityMgr.cancelWaitingDialog();
                Log.e("bindphonerst===", "bindphonerst:" + rst);
                if (rst == null) {
                    rst = "";
                }
                
                if (rst.equals("")) {
                    Toast.makeText(mContext, TipMessSingle.ten_networkerr,
                        Toast.LENGTH_LONG).show();
                    return;
                }
                try {
                    JSONObject json = new JSONObject(rst);
                    String state = json.getString("state");
                    JSONObject jsonState = new JSONObject(state);
                    
                    int code = jsonState.getInt("code");
                    String msgmsg = jsonState.optString("msg");
                    if (code != 1) {
                        Toast.makeText(getContext(), msgmsg, Toast.LENGTH_LONG).show();
                        return;
                    }
                    String msg = json.getString("data");
                    Log.e("Binddata", "Binddata" + msg);

                    if(GlobalConfig.sRegCard==0){
                        if (loginResultSucc != null) {
                            activityMgr.notifyLoginSuccess(loginResultSucc);
                            activityMgr.finishDialogOrActivity();
                        }
                    }else {
                        activityMgr.NewpopViewFromStack();
                        activityMgr.pushViewToStack(new RealViewMust(ownerActivity,activityMgr,loginResultSucc));
                    }
                } catch (JSONException e) {
                    Log.d("BindPhone", "Server returns error msg");
                    e.printStackTrace();
                }
            }
            
            @Override
            public Activity getOwnerActivity() {
                return ownerActivity;
            }
            
            @Override
            protected void onCancelled() {
            }
            
        };
        bindPhoneAsyncTask.execute();
        activityMgr.showWaitingDialog();
    }
    
    private static final String TAG = BindPhoneMustView.class.getSimpleName();
    
    private void startLogin(String platformuid, String pass) {
        final String uname = platformuid;
        final String upass = pass;
        final Map<String, String> params = GuildBaseInfo
            .getInstance()
            .getOneKeyMaybeNoPassParamGuild(mContext, uname, upass, "login");
        if (params == null) {
            Toast.makeText(mContext, "传入参数有误...", Toast.LENGTH_LONG).show();
            return;
        }
        
        // 进行登录请求
        SdkAsyncTask<String> loginSyncTask = new SdkAsyncTask<String>() {
            @Override
            protected String doInBackground() {
                return HttpReq.doGuildRequest(params);
            }
        
            @Override
            protected void onPostExecute(String rst) {
                Log.i(TAG, "onPostExecute rst:" + rst);
    
                activityMgr.cancelWaitingDialog();
                if (rst == null) {
                    rst = "";
                }
            
                if (!"".equals(rst)) {
                    try {
                        JSONObject json = new JSONObject(rst);
                        String state = json.getString("state");
                        JSONObject jsonState = new JSONObject(state);
    
                        int code = jsonState.getInt("code");
                        String msgmsg = jsonState.optString("msg");
                        if (code != 1) {
                            Toast.makeText(getContext(), msgmsg, Toast.LENGTH_LONG).show();
                            return;
                        }
    
                        String msg = json.getString("data");
                        JSONObject msgjson = new JSONObject(msg);
    
                        String user_id = msgjson.optString("id");
                        String token = msgjson.optString("ticket");
                        int time = msgjson.optInt("expires_in");
    
                        if (TextUtils.isEmpty(msgjson.optString("float_window_url"))) {
                            String httpsFloatUrl = msgjson.getString("float_window_url");
                            SpMmkvUtils.putValue(getOwnerActivity(), SpMmkvUtils.KEY_HTTPS_FLOAT_URL, httpsFloatUrl);
                        }
    
                        if (!TextUtils.isEmpty(msgjson.optString("game_discount"))) {
                            String discount = msgjson.getString("game_discount");
                            SpMmkvUtils.putValue(getOwnerActivity(), SpMmkvUtils.KEY_DISCOUNT, discount);
                        }else {
                            SpMmkvUtils.putValue(getOwnerActivity(), SpMmkvUtils.KEY_DISCOUNT, "0");
                        }
    
                        // 进行状态判断
                        DBHelper.SDK_ACCOUNT s_acct = new DBHelper.SDK_ACCOUNT();
                        s_acct.auto_login = 1;
                        s_acct.user_name = uname;
                        s_acct.user_password = upass;
                        s_acct.is_valid = AccountHelper.ACCOUNT_VALID;
                        s_acct.user_id = user_id;
    
                        Local_Account local_acct = new Local_Account();
                        local_acct.username = uname;
                        local_acct.password = upass;
                        local_acct.isValid = AccountHelper.ACCOUNT_VALID;
                        AccountHelper.updateLocalAccounts(local_acct);
    
                        if (dbHelper.isAccountPresent(s_acct)) {
                            dbHelper.updateAccount(s_acct);
                        } else {
                            dbHelper.insertNewAccount(s_acct);
                        }
    
                        QdLoginResult loginResult = new QdLoginResult(user_id, uname, token, String.valueOf(time), "0", "1");
                        GuildBaseInfo.getInstance().SetLoginAuMess(uname, upass, String.valueOf(LoginSwitchManage.getInstance().result_authenticate));
                        GuildBaseInfo.getInstance().setAccountInfo(uname, upass, user_id);
                        GuildBaseInfo.setAcctsInfo(uname, user_id, upass);
    
                        if (FancyManager.getInstance().isAdvertIdBool()) {
                            GameReportHelper.onEventRegister("quick", true);
                        }
                        
                        activityMgr.notifyLoginSuccess(loginResult);
                        activityMgr.finishDialogOrActivity();
    
                        FancyManager.getInstance().CallRegister(QdRegisterCallback.SUCCEEDED, QdRegisterCallback.BY_PHONE);
                        
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(mContext, "当前网络无连接", Toast.LENGTH_LONG)
                        .show();
                }
            }
        
            @Override
            public Activity getOwnerActivity() {
                return ownerActivity;
            }
        
            @Override
            protected void onCancelled() {
            }
        
        };
        loginSyncTask.execute();
        activityMgr.showWaitingDialog();
    }
    
}
